{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "72d32788",
   "metadata": {},
   "source": [
    "# 本周内容：\n",
    ">1.关于麦克风包安装   \n",
    ">2.优化ASR(自动语音识别)机器人   \n",
    ">3.连接图灵机器人(不用自己的字典)   \n",
    ">4.语音合成"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0afc364d",
   "metadata": {},
   "source": [
    "## 关于麦克风包安装\n",
    ">1.安装 speech_recognition\n",
    "pip install SpeechRecognition   \n",
    ">2.安装 PyAudio\n",
    "Not found name \"PyAudio\" moudle   \n",
    ">3.pip install pipwin   pipwin install PyAudio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "065a7d87",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 调用speech_recognition\n",
    "import speech_recognition"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c2be9357",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting pipwin\n",
      "  Downloading pipwin-0.5.2.tar.gz (7.9 kB)\n",
      "Collecting docopt\n",
      "  Downloading docopt-0.6.2.tar.gz (25 kB)\n",
      "Requirement already satisfied: requests in c:\\anaconda\\lib\\site-packages (from pipwin) (2.25.1)\n",
      "Collecting pyprind\n",
      "  Downloading PyPrind-2.11.3-py2.py3-none-any.whl (8.4 kB)\n",
      "Requirement already satisfied: six in c:\\anaconda\\lib\\site-packages (from pipwin) (1.15.0)\n",
      "Requirement already satisfied: beautifulsoup4>=4.9.0 in c:\\anaconda\\lib\\site-packages (from pipwin) (4.9.3)\n",
      "Collecting js2py\n",
      "  Downloading Js2Py-0.71-py3-none-any.whl (1.0 MB)\n",
      "Requirement already satisfied: packaging in c:\\anaconda\\lib\\site-packages (from pipwin) (20.9)\n",
      "Collecting pySmartDL>=1.3.1\n",
      "  Downloading pySmartDL-1.3.4-py3-none-any.whl (20 kB)\n",
      "Requirement already satisfied: soupsieve>1.2 in c:\\anaconda\\lib\\site-packages (from beautifulsoup4>=4.9.0->pipwin) (2.2.1)\n",
      "Collecting tzlocal>=1.2\n",
      "  Downloading tzlocal-4.2-py3-none-any.whl (19 kB)\n",
      "Collecting pyjsparser>=2.5.1\n",
      "  Downloading pyjsparser-2.7.1.tar.gz (24 kB)\n",
      "Collecting pytz-deprecation-shim\n",
      "  Downloading pytz_deprecation_shim-0.1.0.post0-py2.py3-none-any.whl (15 kB)\n",
      "Collecting tzdata\n",
      "  Downloading tzdata-2022.1-py2.py3-none-any.whl (339 kB)\n",
      "Collecting backports.zoneinfo\n",
      "  Downloading backports.zoneinfo-0.2.1-cp38-cp38-win_amd64.whl (38 kB)\n",
      "Requirement already satisfied: pyparsing>=2.0.2 in c:\\anaconda\\lib\\site-packages (from packaging->pipwin) (2.4.7)\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\\anaconda\\lib\\site-packages (from requests->pipwin) (1.26.4)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in c:\\anaconda\\lib\\site-packages (from requests->pipwin) (2020.12.5)\n",
      "Requirement already satisfied: idna<3,>=2.5 in c:\\anaconda\\lib\\site-packages (from requests->pipwin) (2.10)\n",
      "Requirement already satisfied: chardet<5,>=3.0.2 in c:\\anaconda\\lib\\site-packages (from requests->pipwin) (4.0.0)\n",
      "Building wheels for collected packages: pipwin, docopt, pyjsparser\n",
      "  Building wheel for pipwin (setup.py): started\n",
      "  Building wheel for pipwin (setup.py): finished with status 'done'\n",
      "  Created wheel for pipwin: filename=pipwin-0.5.2-py2.py3-none-any.whl size=8776 sha256=98f9761af4afe4f2736cc543731e846ed2b3c4c1858d6f126ea8b0c208b0b3c0\n",
      "  Stored in directory: c:\\users\\86187\\appdata\\local\\pip\\cache\\wheels\\f4\\a8\\76\\372879a40d2d4dd7de23efd867ed37112687429b8d0dda4545\n",
      "  Building wheel for docopt (setup.py): started\n",
      "  Building wheel for docopt (setup.py): finished with status 'done'\n",
      "  Created wheel for docopt: filename=docopt-0.6.2-py2.py3-none-any.whl size=13705 sha256=d041e138782cc193cfcfb8d1d804260527b0596cd8955cfe5a4a45a8dd2f7e93\n",
      "  Stored in directory: c:\\users\\86187\\appdata\\local\\pip\\cache\\wheels\\56\\ea\\58\\ead137b087d9e326852a851351d1debf4ada529b6ac0ec4e8c\n",
      "  Building wheel for pyjsparser (setup.py): started\n",
      "  Building wheel for pyjsparser (setup.py): finished with status 'done'\n",
      "  Created wheel for pyjsparser: filename=pyjsparser-2.7.1-py3-none-any.whl size=25998 sha256=1f15f9f0593053033655fb89910adf0462193c4b2794854518ab437608bf0f98\n",
      "  Stored in directory: c:\\users\\86187\\appdata\\local\\pip\\cache\\wheels\\d5\\88\\34\\ccb5bb40eb3178a134eb293e6c363928c5bcfba0b91031db76\n",
      "Successfully built pipwin docopt pyjsparser\n",
      "Installing collected packages: tzdata, backports.zoneinfo, pytz-deprecation-shim, tzlocal, pyjsparser, pySmartDL, pyprind, js2py, docopt, pipwin\n",
      "Successfully installed backports.zoneinfo-0.2.1 docopt-0.6.2 js2py-0.71 pipwin-0.5.2 pySmartDL-1.3.4 pyjsparser-2.7.1 pyprind-2.11.3 pytz-deprecation-shim-0.1.0.post0 tzdata-2022.1 tzlocal-4.2\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Usage:\n",
      "  pipwin install (<package> | [-r=<file> | --file=<file>]) [--proxy=<proxy>]\n",
      "  pipwin uninstall <package>\n",
      "  pipwin download (<package> | [-r=<file> | --file=<file>]) [-d=<dest> | --dest=<dest>] [--proxy=<proxy>]\n",
      "  pipwin search <package> [--proxy=<proxy>]\n",
      "  pipwin list\n",
      "  pipwin refresh [--log=<log>] [--proxy=<proxy>]\n",
      "  pipwin (-h | --help)\n",
      "  pipwin (-v | --version)\n"
     ]
    }
   ],
   "source": [
    "!pip install pipwin\n",
    "!pipwin instll PyAudio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "f32f504c",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: pipwin in c:\\anaconda\\lib\\site-packages (0.5.2)\n",
      "Requirement already satisfied: requests in c:\\anaconda\\lib\\site-packages (from pipwin) (2.25.1)\n",
      "Requirement already satisfied: packaging in c:\\anaconda\\lib\\site-packages (from pipwin) (20.9)\n",
      "Requirement already satisfied: docopt in c:\\anaconda\\lib\\site-packages (from pipwin) (0.6.2)\n",
      "Requirement already satisfied: six in c:\\anaconda\\lib\\site-packages (from pipwin) (1.15.0)\n",
      "Requirement already satisfied: pySmartDL>=1.3.1 in c:\\anaconda\\lib\\site-packages (from pipwin) (1.3.4)\n",
      "Requirement already satisfied: js2py in c:\\anaconda\\lib\\site-packages (from pipwin) (0.71)\n",
      "Requirement already satisfied: beautifulsoup4>=4.9.0 in c:\\anaconda\\lib\\site-packages (from pipwin) (4.9.3)\n",
      "Requirement already satisfied: pyprind in c:\\anaconda\\lib\\site-packages (from pipwin) (2.11.3)\n",
      "Requirement already satisfied: soupsieve>1.2 in c:\\anaconda\\lib\\site-packages (from beautifulsoup4>=4.9.0->pipwin) (2.2.1)\n",
      "Requirement already satisfied: pyjsparser>=2.5.1 in c:\\anaconda\\lib\\site-packages (from js2py->pipwin) (2.7.1)\n",
      "Requirement already satisfied: tzlocal>=1.2 in c:\\anaconda\\lib\\site-packages (from js2py->pipwin) (4.2)\n",
      "Requirement already satisfied: backports.zoneinfo in c:\\anaconda\\lib\\site-packages (from tzlocal>=1.2->js2py->pipwin) (0.2.1)\n",
      "Requirement already satisfied: pytz-deprecation-shim in c:\\anaconda\\lib\\site-packages (from tzlocal>=1.2->js2py->pipwin) (0.1.0.post0)\n",
      "Note: you may need to restart the kernel to use updated packages.Requirement already satisfied: tzdata in c:\\anaconda\\lib\\site-packages (from tzlocal>=1.2->js2py->pipwin) (2022.1)\n",
      "Requirement already satisfied: pyparsing>=2.0.2 in c:\\anaconda\\lib\\site-packages (from packaging->pipwin) (2.4.7)\n",
      "Requirement already satisfied: chardet<5,>=3.0.2 in c:\\anaconda\\lib\\site-packages (from requests->pipwin) (4.0.0)\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\\anaconda\\lib\\site-packages (from requests->pipwin) (1.26.4)\n",
      "Requirement already satisfied: idna<3,>=2.5 in c:\\anaconda\\lib\\site-packages (from requests->pipwin) (2.10)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in c:\\anaconda\\lib\\site-packages (from requests->pipwin) (2020.12.5)\n",
      "\n"
     ]
    }
   ],
   "source": [
    "pip install pipwin"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "e627bd24",
   "metadata": {},
   "outputs": [],
   "source": [
    "import speech_recognition\n",
    "\n",
    "r = speech_recognition.Recognizer()\n",
    "\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9e27879f",
   "metadata": {},
   "source": [
    "## 2.优化ASR(自动语音识别)机器人"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "9f50dcd1",
   "metadata": {},
   "outputs": [],
   "source": [
    "API_KEY = 'GAaYWbgD93ykIZOg6zlhlrKb'\n",
    "SECRET_KEY = 'PzdSDY0qHnBr5AnB2e7pTXntBgEKL3fy'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "7b5a0b55",
   "metadata": {},
   "outputs": [],
   "source": [
    "# coding=utf-8\n",
    "\n",
    "import sys\n",
    "import json\n",
    "import time\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "\n",
    "    timer = time.perf_counter\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "    if sys.platform == \"win32\":\n",
    "        timer = time.clock\n",
    "    else:\n",
    "        timer = time.time\n",
    "\n",
    "SCOPE = 'audio_voice_assistant_get'  # 有此scope表示有asr能力，没有请在网页里勾选，非常旧的应用可能没有\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "# 获取access_token的函数\n",
    "def fetch_token(API_KEY,SECRET_KEY):\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode('utf-8')\n",
    "    req = Request('http://aip.baidubce.com/oauth/2.0/token', post_data)\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str = result_str.decode()\n",
    "    result = json.loads(result_str)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        if SCOPE and (not SCOPE in result['scope'].split(' ')):  # SCOPE = False 忽略检查\n",
    "            raise DemoError('scope is not correct')\n",
    "        print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "# 语音识别函数      \n",
    "def asr(token,AUDIO_FILE,CUID='123456PYTHON',DEV_PID=1537,RATE=16000):\n",
    "    speech_data = []\n",
    "    with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "        speech_data = speech_file.read()\n",
    "    length = len(speech_data)\n",
    "    if length == 0:\n",
    "        raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "    params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID}\n",
    "    params_query = urlencode(params);\n",
    "    headers = {\n",
    "        'Content-Type': 'audio/' + AUDIO_FILE[-3:] + '; rate=' + str(RATE),\n",
    "        'Content-Length': length\n",
    "    }\n",
    "\n",
    "    url = 'http://vop.baidu.com/server_api' + \"?\" + params_query\n",
    "    req = Request('http://vop.baidu.com/server_api' + \"?\" + params_query, speech_data, headers)\n",
    "    try:\n",
    "        begin = timer()\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "        print(\"Request time cost %f\" % (timer() - begin))\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "\n",
    "    if (IS_PY3):\n",
    "        result_str = str(result_str, 'utf-8')\n",
    "    print(result_str)\n",
    "    with open(\"result.txt\", \"w\") as of:\n",
    "        of.write(result_str)\n",
    "    return result_str"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "dceeaea8",
   "metadata": {},
   "outputs": [],
   "source": [
    "import speech_recognition\n",
    "\n",
    "r = speech_recognition.Recognizer()\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"2.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8161de45",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
